<template>
    <div class="login-container">
        <div class="login-box">
            <div class="login-title">中医智诊后台管理系统</div>
            <div class="login-type">
                <span :class="{ active: loginType === 'account' }" @click="loginType = 'account'">账号密码登录</span>
                <span :class="{ active: loginType === 'phone' }" @click="loginType = 'phone'">手机号登录</span>
            </div>
            <el-form :model="formData" :rules="rules" ref="formRef">
                <!-- 账号密码登录 -->
                <template v-if="loginType === 'account'">
                    <el-form-item prop="username">
                        <el-input v-model="formData.username" placeholder="账号" :prefix-icon="User"
                             />
                    </el-form-item>

                    <el-form-item prop="password">
                        <el-input v-model="formData.password" type="password" placeholder="密码" :prefix-icon="Lock"
                            show-password />
                    </el-form-item>
                </template>

                <!-- 手机号登录 -->
                <template v-else>
                    <el-form-item prop="phone">
                        <el-input v-model="formData.phone" placeholder="手机号" :prefix-icon="Phone" />
                    </el-form-item>

                    <el-form-item prop="smsCode">
                        <div class="sms-code-container">
                            <el-input v-model="formData.smsCode" placeholder="验证码" :prefix-icon="Key" />
                            <el-button type="primary" :disabled="!!countdown" @click="sendSmsCode" class="send-code-btn"
                                :loading="sendSmsCodeLoading">
                                {{ countdown ? `${countdown}s后重试` : '发送验证码' }}
                            </el-button>
                        </div>
                    </el-form-item>
                </template>

                <el-form-item prop="captcha">
                    <div class="captcha-container">
                        <el-input v-model="formData.captcha" placeholder="图形验证码" style="width: 200px" 
                        @keyup.enter="handleSubmit"/>
                        <canvas ref="captchaCanvas" @click="refreshCaptcha"
                            style="cursor: pointer; margin-left: 10px"></canvas>
                    </div>
                </el-form-item>

                <el-button type="primary" :loading="loading" class="submit-btn" @click="handleSubmit">
                    {{ isLogin ? '登录' : '注册' }}
                </el-button>

                <div class="switch-action">
                    <a @click="switchMode">{{ isLogin ? '还没有账号？立即注册' : '已有账号？立即登录' }}</a>
                </div>
            </el-form>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, nextTick, onMounted } from 'vue'
import { User, Lock, Phone, Key } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'
import { useUserStore } from '@/store/user'

const router = useRouter()
const loading = ref(false)
const formRef = ref(null)
const isLogin = ref(true)
const loginType = ref('account')
const countdown = ref(0)
const sendSmsCodeLoading = ref(false)

const formData = reactive({
    username: '',
    password: '',
    confirmPassword: '',
    captcha: '',
    phone: '',
    smsCode: ''
})

const captchaCanvas = ref(null)
const captchaText = ref('')

// 生成随机验证码
const generateCaptcha = () => {
    const canvas = captchaCanvas.value
    const ctx = canvas.getContext('2d')
    canvas.width = 100
    canvas.height = 40

    // 生成随机字符
    const characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    let code = ''
    for (let i = 0; i < 4; i++) {
        code += characters.charAt(Math.floor(Math.random() * characters.length))
    }
    captchaText.value = code

    // 绘制背景
    ctx.fillStyle = '#f0f0f0'
    ctx.fillRect(0, 0, canvas.width, canvas.height)

    // 绘制文字
    ctx.font = 'bold 24px Arial'
    ctx.fillStyle = '#333'
    ctx.textAlign = 'center'
    ctx.textBaseline = 'middle'

    // 随机旋转每个字符
    for (let i = 0; i < code.length; i++) {
        const x = 20 + i * 20
        const y = canvas.height / 2
        ctx.save()
        ctx.translate(x, y)
        ctx.rotate((Math.random() - 0.5) * 0.3)
        ctx.fillText(code[i], 0, 0)
        ctx.restore()
    }

    // 添加干扰线
    for (let i = 0; i < 3; i++) {
        ctx.beginPath()
        ctx.strokeStyle = `rgb(${Math.random() * 255},${Math.random() * 255},${Math.random() * 255})`
        ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height)
        ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height)
        ctx.stroke()
    }

    // 添加干扰点
    for (let i = 0; i < 50; i++) {
        ctx.fillStyle = `rgb(${Math.random() * 255},${Math.random() * 255},${Math.random() * 255})`
        ctx.fillRect(Math.random() * canvas.width, Math.random() * canvas.height, 2, 2)
    }
}

// 刷新验证码
const refreshCaptcha = () => {
    generateCaptcha()
    formData.captcha = ''
}

// 验证码校验规则
const validateCaptcha = (rule, value, callback) => {
    if (!value) {
        callback(new Error('请输入图片验证码'))
    } else if (value.toUpperCase() !== captchaText.value) {
        callback(new Error('验证码错误'))
    } else {
        callback()
    }
}

const validateConfirmPassword = (rule, value, callback) => {
    if (!value) {
        callback(new Error('请再次输入密码'))
    } else if (value !== formData.password) {
        callback(new Error('两次输入密码不一致'))
    } else {
        callback()
    }
}

// 手机号验证规则
const validatePhone = (rule, value, callback) => {
    if (!value) {
        callback(new Error('请输入手机号'))
    } else if (!/^1[3-9]\d{9}$/.test(value)) {
        callback(new Error('请输入正确的手机号'))
    } else {
        callback()
    }
}

// 验证码验证规则
const validateSmsCode = (rule, value, callback) => {
    if (!value) {
        callback(new Error('请输入验证码'))
    } else if (!/^\d{6}$/.test(value)) {
        callback(new Error('验证码格式不正确'))
    } else {
        callback()
    }
}

const rules = {
    username: [
        { required: true, message: '请输入账号', trigger: 'blur' },
        { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
    ],
    phone: [
        { validator: validatePhone, trigger: 'blur' }
    ],
    smsCode: [
        { validator: validateSmsCode, trigger: 'blur' }
    ],
    confirmPassword: [
        { validator: validateConfirmPassword, trigger: 'blur' }
    ],
    captcha: [
        { required: true, message: '请输入图片验证码', trigger: 'blur' },
        { validator: validateCaptcha, trigger: 'blur' }
    ]
}

const switchMode = () => {
    ElMessage.error('不支持注册，只能由管理员添加！')
    return
}

// 组件挂载时生成验证码
onMounted(() => {
    generateCaptcha()
})

// 发送短信验证码
const sendSmsCode = async () => {
    await formRef.value.validateField('phone')
    sendSmsCodeLoading.value = true

    try {
        await request({
            url: '/employee/sendSmsCode',
            method: 'post',
            data: { phone: formData.phone }
        })
        ElMessage.success('验证码发送成功')
        countdown.value = 60
        const timer = setInterval(() => {
            countdown.value--
            if (countdown.value <= 0) {
                clearInterval(timer)
            }
        }, 1000)
    } catch (error) {
        console.error('发送验证码失败:', error)
    } finally {
        sendSmsCodeLoading.value = false
    }
}

const handleSubmit = async () => {
    if (!formRef.value) return

    try {
        await formRef.value.validate()
        loading.value = true

        if (isLogin.value) {
            let res
            // 根据登录方式调用不同的接口
            if (loginType.value === 'account') {
                // 账号密码登录
                res = await request({
                    url: '/employee/login',
                    method: 'post',
                    data: {
                        username: formData.username,
                        password: formData.password,
                    }
                })
            } else {
                // 手机号登录
                res = await request({
                    url: '/employee/loginByPhone',
                    method: 'post',
                    data: {
                        phone: formData.phone,
                        code: formData.smsCode
                    }
                })
            }

            // 保存用户信息
            // localStorage.setItem('userInfo', JSON.stringify(res.data))
            useUserStore().setUserInfo(res.data)

            // 先提示成功
            ElMessage.success('登录成功')

            // 使用 nextTick 确保在 DOM 更新后再跳转
            nextTick(() => {
                router.push('/')
            })
            // 重新生成验证码
            refreshCaptcha()
        } else {
            // 注册请求
            await request({
                url: '/employee/register',
                method: 'post',
                data: {
                    username: formData.username,
                    password: formData.password
                }
            })

            ElMessage.success('注册成功')
            isLogin.value = true
            formRef.value.resetFields()
        }
    } catch (error) {
        console.error('登录失败:', error)
    } finally {
        loading.value = false
    }
}
</script>

<style scoped>
.login-container {
    height: 100vh;
    background-image: url('@/assets/images/login-background.jpg');
    background-size: cover;
    background-position: center;
    display: flex;
    justify-content: center;
    align-items: center;
}

.login-box {
    width: 400px;
    padding: 30px;
    background: rgba(255, 255, 255, 0.95);
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.login-title {
    text-align: center;
    font-size: 18px;
    color: #333;
    margin-bottom: 30px;
}

:deep(.el-input__wrapper) {
    background-color: #fff;
}

:deep(.el-input__inner) {
    height: 40px;
}

.submit-btn {
    width: 100%;
    height: 40px;
    font-size: 16px;
}

:deep(.el-checkbox__label) {
    color: #606266;
}

.switch-action {
    text-align: center;
    margin-top: 15px;
}

.switch-action a {
    color: #409EFF;
    cursor: pointer;
    text-decoration: none;
}

.switch-action a:hover {
    color: #66b1ff;
}

.captcha-container {
    display: flex;
    align-items: center;
}

.login-type {
    display: flex;
    justify-content: center;
    margin-bottom: 20px;
}

.login-type span {
    padding: 0 15px;
    cursor: pointer;
    color: #606266;
    position: relative;
}

.login-type span.active {
    color: #409EFF;
}

.login-type span.active::after {
    content: '';
    position: absolute;
    bottom: -5px;
    left: 50%;
    transform: translateX(-50%);
    width: 20px;
    height: 2px;
    background-color: #409EFF;
}

.sms-code-container {
    display: flex;
    gap: 10px;
}

.send-code-btn {
    width: 120px;
    flex-shrink: 0;
}
</style>